<template>
    <div>
        <el-form label-width="90px" label-position="left">
            <el-form-item label="sku名称">
                <el-input placeholder="请输入sku名称" v-model="skuParams.skuName"></el-input>
            </el-form-item>
            <el-form-item label="价格（元）">
                <el-input placeholder="请输入价格（元）" type="number" v-model="skuParams.price"></el-input>
            </el-form-item>
            <el-form-item label="重量（克）">
                <el-input placeholder="请输入重量（克）" type="number" v-model="skuParams.weight"></el-input>
            </el-form-item>
            <el-form-item label="sku描述">
                <el-input type="textarea" placeholder="请输入sku描述" v-model="skuParams.skuDesc"></el-input>
            </el-form-item>
            <el-form-item label="平台属性">
                <el-form inline label-width="50px">
                    <el-form-item style="width: 200px;margin-bottom: 20px;" v-for="item in attrArr" :key="item.id"
                        :label="item.attrName">
                        <!-- 收集到属性对象item.attrIdAndValueId中 -->
                        <el-select v-model="item.attrIdAndValueId">
                            <el-option v-for="(attrValue) in item.attrValueList" :label="attrValue.valueName"
                                :key="attrValue.id" :value="`${item.id}:${attrValue.id}`"></el-option>
                        </el-select>
                    </el-form-item>
                </el-form>
            </el-form-item>
            <el-form-item label="销售属性">
                <el-form inline>
                    <el-form-item style="width: 200px;" v-for="item in saleArr" :label="item.saleAttrName" :key="item.id">
                        <el-select v-model="item.saleIdAndValueId">
                            <el-option v-for="saleAttrValue in item.spuSaleAttrValueList" :key="saleAttrValue.id"
                                :label="saleAttrValue.saleAttrName" :value="`${item.id}:${saleAttrValue.id}`"></el-option>
                        </el-select>
                    </el-form-item>
                </el-form>
            </el-form-item>
            <el-form-item label="图片名称">
                <el-table border :data="imgArr" ref="table">
                    <el-table-column type="selection" width="80px" align="center"></el-table-column>
                    <el-table-column label="图片名称" prop="imgName"></el-table-column>
                    <el-table-column label="图片" align="center">
                        <!-- @vue-ignore -->
                        <template #="{ row, $index }">
                            <img :src="row.imgUrl" :alt="row.imgName" style="width: 100px;height: 100px;object-fit: cover;">
                        </template>
                    </el-table-column>
                    <el-table-column label="操作">
                        <!-- @vue-ignore -->
                        <template #="{ row, $index }">
                            <el-button type="warning" @click="handler(row)">设置默认</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" size="mini" @click="save">保存</el-button>
                <el-button type="warning" size="mini" @click="cancel">取消</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script setup lang="ts">
import { reqAttr } from '@/api/product/attr';
import { reqSpuImageList, reqSpuHasSaleAttr } from '@/api/product/spu';
import { reqAddSku } from '@/api/product/sku';
import { SkuData } from "@/api/product/spu/types"
import { reactive, ref } from "vue";
import { ElMessage } from 'element-plus';
// 存储平台属性
let attrArr = ref<any>([])
// 存储平台属性
const saleArr = ref<any>([])
// 存储照片墙属性
const imgArr = ref<any>([])
// 绑定table实例
const table = ref<any>()
// 存储接口所需要的数据
const skuParams = reactive<SkuData>({
    category3Id: "",
    spuId: "",
    tmId: "",
    skuName: "",
    price: "",
    weight: "",
    skuDesc: "",
    // @ts-ignore
    skuAttrValueList: [],
    skuSaleAttrValueList: [],
    skuDefaultImg: ""
})
// 接收父组件传递的方法
const emit = defineEmits(["changeScene"]);
// 切换显示元素为skuForm
const cancel = () => {
    emit("changeScene", { flag: 0, params: '' });
};
const initSkuData = async (c1Id: number | string, c2Id: string | number, spu: any) => {
    skuParams.category3Id = spu.category3Id,
        skuParams.spuId = spu.id,
        skuParams.tmId = spu.tmId
    // 获取平台属性
    const res = await reqAttr(c1Id, c2Id, spu.category3Id)
    if (res.code === 200) {
        attrArr.value = res.data
    }
    // 获取销售属性
    const result1 = await reqSpuHasSaleAttr(spu.id)
    if (result1.code === 200) {
        saleArr.value = result1.data
        console.log(result1);

    }
    // 获取照片墙数据
    const result2 = await reqSpuImageList(spu.id)
    if (result2.code === 200) {
        imgArr.value = result2.data
    }
}
// 设置默认方法的回调
const handler = (row: any) => {
    skuParams.skuDefaultImg = row.imgUrl
    // 点击的时候直接清空选项
    table.value.clearSelection()
    /*
        或者
           imgArr.value.forEach((element:any) => {
        table.value.toggleRowSelection(element, false)
        });

    */

    // 点击谁谁前面的复选框要勾上
    table.value.toggleRowSelection(row, true)
}
// 保存按钮的回调
const save = async () => {
    // 整理参数
    // 平台属性
    skuParams.skuAttrValueList = attrArr.value.reduce((pre: any, next: any) => {
        if (next.attrIdAndValueId) {
            // 切割字符串，返回一个数组 eg: 1->attrId:2->valueId
            let [attrId, valueId] = next.attrIdAndValueId.split(":")
            pre.push({
                attrId,
                valueId
            })
        }
        return pre
    }, [])
    // 整理销售属性
    skuParams.skuSaleAttrValueList = saleArr.value.reduce((prev: any, next: any) => {
        if (next.saleIdAndValueId) {
            let [saleAttrId, saleAttrValueId] = next.saleIdAndValueId.split(":")
            prev.push({
                saleAttrId,
                saleAttrValueId
            })
        }
        return prev
    }, [])

    // 发请求·
    const res = await reqAddSku(skuParams)
    // 成功
    if (res.code === 200) {
        ElMessage.success("保存成功")
        // 调用父组件的方法
        emit("changeScene", { flag: 0, params: '' });
    }
    // 失败
    else {
        ElMessage.error("保存失败")
    }
}
// 当前子组件的数据对外暴露
defineExpose({
    initSkuData
})
</script>

<style scoped></style>